<?php

namespace app\api\controller;

use app\api\model\question\Questionnaire;
use app\api\model\User as Model;
use app\api\model\user\Application;
use app\common\model\user\Paper;
use app\common\model\user\PaperTopic;
use think\facade\Cache;

class Student extends Controller
{
    public function details($student_id, $question_id)
    {
        $detail = Model::detail($student_id);
        $question = \app\common\model\questionnaire\Questionnaire::detail($question_id);
        return $this->renderSuccess(compact('detail', 'question'));

    }

    public function handPaper($application_id = 0, $question_id = 0)
    {
        $data = $this->request->param();
        if (empty($application_id) || empty($question_id)) {
            return $this->renderError('系统升级中');
        }
        Cache::set("paper" . $application_id . $question_id, $data['answerSheet']);
        return $this->renderSuccess("提交成功");
    }

    public function sendPaper($application_id, $question_id, $examsign_file_id)
    {
        $application = Application::detail($application_id, ['job', 'subject_level']);
        if (!$application) {
            return $this->renderError("学员信息不存在");
        }

        $topic = Questionnaire::detail($question_id);
        if (!$topic) {
            return $this->renderError("题库不存在");
        }

        $answerSheet = Cache::get("paper" . $application_id . $question_id);

        //分数
        $sun_score = 0;
        $paper_topic = [];
        foreach ($answerSheet as $item) {
            $is_right = 0;
            if ($item["qt_type"] == 3) {
                if (!is_array($item['choose_answer'])) {
                    $item['choose_answer'] = explode(',', $item['choose_answer']);
                }
                sort($item['choose_answer']);
                if (!is_array($item['correct_answer'])) {
                    $item['correct_answer'] = explode(',', $item['correct_answer']);
                }
                sort($item['correct_answer']);
                $choose_answer = implode(',', $item['choose_answer']);
                $correct_answer = implode(',', $item['correct_answer']);
                if ($choose_answer == $correct_answer) {
                    $sun_score += $item['score'];
                    $is_right = 1;
                }
            } else {
                $choose_answer = $item['choose_answer'];
                $correct_answer = $item['correct_answer'];
                if ($choose_answer == $correct_answer) {
                    $sun_score += $item['score'];
                    $is_right = 1;
                }
            }

            $paper_topic[] = [
                'is_right' => $is_right,
                'question_id' => $item['question_id'],
                'title' => $item['title'],
                'qt_type' => $item['qt_type'],
                'qt_item' => $item['qt_item'] ? json_encode($item['qt_item'], 320) : '',
                'correct_answer' => $correct_answer,
                'choose_answer' => $choose_answer,
                'exam_score' => $item['score'],
                'create_time' => time(),
                'store_id' => $this->storeId,
            ];
        }
        //如果未及格
        if ($sun_score < $topic->passing_mark) {
            $paper = (new Paper())->where([
                ['application_id', '=', $application->application_id],
                ['exam_score', '<', $topic->passing_mark],
                ['is_delete', '=', 0],
            ])->find();
            if ($paper) {
                $res = $this->sendPassPaperTopic($application->application_id, $examsign_file_id);
                return $this->renderSuccess($res);
            }
        }
        //记录试卷
        $paper_id = (new Paper())->insertGetId([
            'paper_title' => $application->subject->subject_name . $application->subject_level->level_name . '考试',
            'passing_mark' => $topic->passing_mark,
            'user_id' => $application->user_id,
            'application_id' => $application->application_id,
            'question_id' => $question_id,
            'exam_score' => $sun_score,
            'examsign_file_id' => $examsign_file_id,
            'store_id' => $this->storeId,
            'create_time' => time(),
        ]);
        //记录试卷题目
        foreach ($paper_topic as &$item) {
            $item['paper_id'] = $paper_id;
        }
        (new PaperTopic())->insertAll($paper_topic);

        $application->exam_score = $sun_score;
        $application->examsign_file_id = $examsign_file_id;
        $application->channel_id = $this->channelId;
        $application->save();
        return $this->renderSuccess([
            'application_id' => $application->application_id,
            'question_id' => $question_id,
            'paper_id' => $paper_id
        ]);
    }

    public function sendPassPaperTopic($application_id, $examsign_file_id)
    {
        $application = Application::detail((int)$application_id);
        if (!$application) {
            return $this->renderError("学员信息不存在");
        }
        $model = new Questionnaire();
        $list = $model->getTestInfo($application->subject_level_id);

        $topic = $list['topic'];
        $item_list = $list['item'];
        $exam_score = $this->oRand();
        $wrong_count = (100 - $exam_score) / 2;
        if ($wrong_count > 0) {
            $wrongList = array_rand($item_list, $wrong_count);
            if (!is_array($wrongList)) {
                $index = $wrongList;
                $question = $item_list[$index];
                $options = $question['qt_item'];
                $item_list[$index]['correct_answer'] = $question['answer'];
                if ($question['qt_type'] == 1) {
                    //判断题
                    $item_list[$index]['choose_answer'] = $this->getWrongAnswer($options, $question['answer']);

                } else if ($question['qt_type'] == 2) {
                    //单选题
                    $item_list[$index]['choose_answer'] = $this->getWrongAnswer($options, $question['answer']);

                } else if ($question['qt_type'] == 3) {
                    //多选题
                    $item_list[$index]['choose_answer'] = $this->getMakeWrongAnswer($options, $question['answer']);
                }
            } else {
                foreach ($wrongList as $index) {
                    $question = $item_list[$index];
                    $item_list[$index]['correct_answer'] = $question['answer'];
                    $options = $question['qt_item'];
                    if ($question['qt_type'] == 1) {
                        //判断题
                        $item_list[$index]['choose_answer'] = $this->getWrongAnswer($options, $question['answer']);
                    } else if ($question['qt_type'] == 2) {
                        //单选题
                        $item_list[$index]['choose_answer'] = $this->getWrongAnswer($options, $question['answer']);
                    } else if ($question['qt_type'] == 3) {
                        //多选题
                        $item_list[$index]['choose_answer'] = $this->getMakeWrongAnswer($options, $question['answer']);
                    }
                }
            }
        }

        $answerSheet = $item_list;


        //分数
        $sun_score = 0;
        $paper_topic = [];
        foreach ($answerSheet as $item) {

            if (empty($item['choose_answer']) && empty($item['correct_answer'])) {
                $item['choose_answer'] = $item['answer'];
                $item['correct_answer'] = $item['answer'];
            }

            $is_right = 0;
            if ($item["qt_type"] == 3) {
                if (!is_array($item['choose_answer'])) {
                    $item['choose_answer'] = explode(',', $item['choose_answer']);
                }
                sort($item['choose_answer']);
                if (!is_array($item['correct_answer'])) {
                    $item['correct_answer'] = explode(',', $item['correct_answer']);
                }
                sort($item['correct_answer']);
                $choose_answer = implode(',', $item['choose_answer']);
                $correct_answer = implode(',', $item['correct_answer']);
                if ($choose_answer == $correct_answer) {
                    $sun_score += $item['score'];
                    $is_right = 1;
                }
            } else {
                $choose_answer = $item['choose_answer'];
                $correct_answer = $item['correct_answer'];
                if ($choose_answer == $correct_answer) {
                    $sun_score += $item['score'];
                    $is_right = 1;
                }
            }

            $paper_topic[] = [
                'is_right' => $is_right,
                'question_id' => $item['question_id'],
                'title' => $item['title'],
                'qt_type' => $item['qt_type'],
                'qt_item' => $item['qt_item'] ? json_encode($item['qt_item'], 320) : '',
                'correct_answer' => $correct_answer,
                'choose_answer' => $choose_answer,
                'exam_score' => $item['score'],
                'create_time' => time(),
                'store_id' => $this->storeId,
            ];
        }

        //记录试卷
        $paper_id = (new Paper())->insertGetId([
            'paper_title' => $application->subject->subject_name . $application->subject_level->level_name . '考试',
            'passing_mark' => $topic->passing_mark,
            'user_id' => $application->user_id,
            'application_id' => $application->application_id,
            'question_id' => $topic->question_id,
            'exam_score' => $sun_score,
            'examsign_file_id' => $examsign_file_id,
            'store_id' => $this->storeId,
            'create_time' => time(),
        ]);
        //记录试卷题目
        foreach ($paper_topic as &$item) {
            $item['paper_id'] = $paper_id;
        }
        (new PaperTopic())->insertAll($paper_topic);

        $application->exam_score = $sun_score;
        $application->examsign_file_id = $examsign_file_id;
        $application->channel_id = $this->channelId;
        $application->save();

        return [
            'application_id' => $application->application_id,
            'question_id' => $topic->question_id,
            'paper_id' => $paper_id
        ];
    }

    public function getTestInfo($application_id = 0)
    {
        $application = Application::detail((int)$application_id);
        if (!$application) {
            return $this->renderError("学员信息不存在");
        }
        $model = new Questionnaire();
        $list = $model->getTestInfo($application->subject_level_id);
        if ($list) {
            return $this->renderSuccess($list);
        }
        return $this->renderError($model->getError() ?: '系统升级中');
    }

    public function oRand()
    {
        $num = rand(60, 98);
        if ($num % 2 != 0) {
            $num = $this->oRand();
        }
        return $num;
    }

    /**
     * 获取随机错误答案
     * @param array $options 题目选项
     * @param string $correctAnswer 正确答案
     * @return string
     */
    public function getWrongAnswer($options, $correctAnswer): string
    {
        $wrongList = [];
        //筛选出错误答案
        foreach ($options as $value) {
            if ($value['item'] != $correctAnswer) {
                $wrongList[] = $value['item'];
            }
        }
        if (!$wrongList) {
            return '';
        }
        $index = rand(0, count($wrongList) - 1);
        $wrongItem = $wrongList[$index];
        return $wrongItem;
    }

    /**
     * 获取随机组合错误答案
     * @param array $options 题目选项
     * @param string $correctAnswer 正确答案
     * @return string
     */
    public function getMakeWrongAnswer($options, $correctAnswer): string
    {

        //选择必须至少选择两项，否则视为未选
        if (is_array($options) && count($options) > 2) {
            $wrongList = [];
            $randWrongList = array_rand($options, rand(2, count($options) - 1));
            foreach ($randWrongList as $index) {
                $wrongList[] = $options[$index]['item'];
            }
            $wrongItem = implode(',', $wrongList);

            //如果生成为正确答案，则重新生成
            if ($wrongItem == $correctAnswer) {
                $wrongItem = $this->getMakeWrongAnswer($options, $correctAnswer);
            }
        } else {
            $wrongItem = '';
        }
        return $wrongItem;
    }

}
